package com.xca.znb.view;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.xca.znb.R;
import com.xca.znb.contact.FriendsContact;
import com.xca.znb.entity.Collect;
import com.xca.znb.entity.Trends;
import com.xca.znb.entity.User;
import com.xca.znb.model.impl.FriendsImpl;
import com.xca.znb.presenter.FriendsPresenter;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class FriendsFragment extends Fragment implements View.OnClickListener , FriendsContact {
    private View friends_fragment ;
    private ImageButton MyPublishBtn , FriendsToPublishBtn ;
    private TextView FriendsLatest , FriendsConcern ;
    private FriendsPresenter presenter ;
    private ArrayAdapter<Trends> adapter ;
    private ArrayAdapter<String> adapterImg ;
    private  List<Trends> trendsList ;
    private List<Trends> collectTrends ;
    private ListView listView ;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (friends_fragment == null){
            friends_fragment = inflater.inflate(R.layout.fragment2 , container , false);
        }
        FriendsImpl friendsImpl = new FriendsImpl(getActivity());
        presenter = new FriendsPresenter(this , friendsImpl);
        MyPublishBtn = friends_fragment.findViewById(R.id.my_publish_btn) ;
        FriendsLatest = friends_fragment.findViewById(R.id.friends_latest) ;
        FriendsConcern = friends_fragment.findViewById(R.id.friends_concern) ;
        FriendsToPublishBtn = friends_fragment.findViewById(R.id.to_publish_btn) ;
        listView = friends_fragment.findViewById(R.id.friends_recyclerView);


        onFriendsMyPublishBtnClick();
        onFriendsLatestClick();
        onFriendsConcernClick();
        onFriendsToPublishBtnClick();
        FriendsLatest.setSelected(true);

        return friends_fragment ;
    }



    private void trendsAdapter(List<Trends> list){

        adapter = new ArrayAdapter<Trends>(requireActivity(), R.layout.friends_circle_item ,R.id.show_phone ,list){
            ArrayList<String> imgList = new ArrayList<>();
            public View getView(int position , View converView , ViewGroup parent){
                View view = super.getView(position, converView, parent);
                ImageView userImg = view.findViewById(R.id.show_avatar);
                TextView userName = view.findViewById(R.id.show_phone);
                TextView userPhone = view.findViewById(R.id.show_publish_time);
                ImageButton enterStore = view.findViewById(R.id.enter_store);
                ImageButton addCollect = view.findViewById(R.id.add_store_collection);
                TextView text = view.findViewById(R.id.show_publish_text);
                GridView images = view.findViewById(R.id.show_publish_img);

                Trends trends = getItem(position);
                if (trends != null){
                    String uerPhone = trends.getPublisher();
                    User user = presenter.getUserByPhone(uerPhone);
                    if (user != null){
                        Glide.with(getActivity())
                                        .load(user.getConcern())
                                                .into(userImg);
                       // userImg.setImageResource(R.drawable.my_publish);
                        if (user.getName()==null){
                            userName.setText(trends.getPublisher());
                        }else {
                            userName.setText(user.getName());
                            userPhone.setText(trends.getPublisher());
                        }
                    }
                    enterStore.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(getActivity(), EnterStoreActivity.class);
                            intent.putExtra("salesPhone" ,trends.getPublisher());
                            startActivity(intent);
                        }
                    });

                    SharedPreferences sharedPreferences = getActivity().getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
                    String phone = sharedPreferences.getString("phone" , "");
                    Collect collect = presenter.getCollect(trends.getPublisher() , "store" , phone);
                    if (collect != null){
                        addCollect.setVisibility(View.GONE);
                    }else {
                        addCollect.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                presenter.addCollect(trends.getPublisher() , "store" , phone);
                                Collect collect = presenter.getCollect(trends.getPublisher() , "store" , phone);
                                if (collect != null){
                                    addCollect.setVisibility(View.GONE);
                                    setAllAdapter();
                                    Toast.makeText(getActivity(), "已关注", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }

                    text.setText(trends.getText());

                    imgList.clear();
                    String jsonImgPath = trends.getImg_list();
                    String[] imgPath = convertJsonToArray(jsonImgPath);
                    for (String img : imgPath){
                        imgList.add(img);
                    }
                    imgItemAdapter();
                    images.setAdapter(adapterImg);
                    adapter.notifyDataSetChanged();
                }

                return view ;
            }
            void imgItemAdapter(){
                adapterImg = new ArrayAdapter<String>(getActivity(), R.layout.friends_img_item , R.id.friends_circle_text_item , imgList){
                    public View getView(int position , View converView , ViewGroup parents){
                        View view = super.getView(position, converView, parents);
                        TextView showText = view.findViewById(R.id.friends_circle_text_item);
                        ImageView showImg = view.findViewById(R.id.friends_circle_img_item);
                        String imgPath = imgList.get(position);

                        Bitmap bitmap = stringPathToBitmap(imgPath);
                        if (bitmap != null){
                            showImg.setImageBitmap(bitmap);
                        }

//                        Glide.with(getActivity())
//                                .load(imgPath)
//                                .placeholder(showImg.getDrawable())
//                                .dontAnimate()
//                                .into(showImg)
//                                ;
                        return view ;
                    }
                };
            }
        };
    }


    public Bitmap stringPathToBitmap(String imagePath) {
        try {
            // 使用BitmapFactory.decodeFile方法将图片路径转换为Bitmap对象
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

            if (bitmap != null) {
                return bitmap;
            } else {
                // 图片加载失败处理
                // Log.e("ImageLoadError", "Failed to load image from path: " + imagePath);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 异常处理
            return null;
        }
    }


    private static  String[] convertJsonToArray(String jsonString){
        String[] imgPathArray = null ;
        try {
            JSONArray jsonArray = new JSONArray(jsonString);
            imgPathArray = new String[jsonArray.length()] ;
            for (int i = 0 ; i < jsonArray.length() ; i++){
                imgPathArray[i] = jsonArray.getString(i) ;
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return imgPathArray ;
    }


    private void setAllAdapter(){
        trendsList = presenter.getTrends();
        trendsAdapter(trendsList);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    private void setCollectAdapter(){
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");
        collectTrends = presenter.friendsList(phone);
        trendsAdapter(collectTrends);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }


    @Override
    public void onResume() {
        super.onResume();
        trendsList  = presenter.getTrends();
        if (FriendsLatest.isSelected()){
            setAllAdapter();
        } else if (FriendsConcern.isSelected()) {
            setCollectAdapter();
        }
    }

    @Override
    public void onClick(View v) {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");
        if (v.getId() == R.id.my_publish_btn){
            Intent intent = new Intent(getActivity() , MyFriendsPublish.class);
            startActivity(intent);
        }
        else if (v.getId() == R.id.friends_latest) {
            FriendsLatest.setSelected(true);
            FriendsConcern.setSelected(false);
            setAllAdapter();
        } else if (v.getId() == R.id.friends_concern) {
            FriendsLatest.setSelected(false);
            FriendsConcern.setSelected(true);
            setCollectAdapter();
        }
        else if (v.getId() == R.id.to_publish_btn) {
            Intent intent = new Intent(FriendsFragment.this.getContext() , PublishDynamicActivity.class) ;
            startActivity(intent);
        }
    }




    @Override
    public void onFriendsMyPublishBtnClick() {
        MyPublishBtn.setOnClickListener(this);
    }

    @Override
    public void onFriendsLatestClick() {
        FriendsLatest.setOnClickListener(this);
    }

    @Override
    public void onFriendsConcernClick() {
        FriendsConcern.setOnClickListener(this);
    }

    @Override
    public void onFriendsToPublishBtnClick() {
        FriendsToPublishBtn.setOnClickListener(this);
    }
}
